﻿using System;
using System.Collections.Generic;
using System.Text;

namespace EssentialWebFramework.Utils
{
    /// <summary>
    /// 通用比较类
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class GeneralEqualityComparer<T> : IEqualityComparer<T>
    {
        /// <summary>
        /// 获取属性值的 Func
        /// </summary>
        private Func<T, object>[] propertyFuncs;

        /// <summary>
        /// ctor
        /// </summary>
        /// <param name="propertyFuncs"></param>
        public GeneralEqualityComparer(params Func<T, object>[] propertyFuncs)
        {
            this.propertyFuncs = propertyFuncs;
        }
        
        /// <summary>
        /// Equals
        /// </summary>
        /// <param name="x"></param>
        /// <param name="y"></param>
        /// <returns></returns>
        public bool Equals(T x, T y)
        {
            if (x == null || y == null)
            {
                return false;
            }

            foreach (var func in this.propertyFuncs)
            {
                if (!func(x).Equals(func(y)))   // 使用 == 时为对象之间的比较，结果可能不正确（比如对于 string 类型的数据）
                {
                    return false;
                }
            }

            return true;
        }

        /// <summary>
        /// GetHashCode
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public int GetHashCode(T obj)
        {
            if (obj == null)
            {
                return 0;
            }

            HashCode hashCode = new HashCode();
            foreach (var func in this.propertyFuncs)
            {
                hashCode.Add(func(obj));
            }

            return hashCode.ToHashCode();
        }
    }
}
